<template>
  <a-card :loading="cardLoading" :bordered="false" style="height: 100%">
    <a-spin :spinning="loading">
      <a-input-search
        v-model="searchValue"
        @search="handleSearch"
        style="width: 100%; margin-top: 10px"
        placeholder="请输入核算单元名称"
        enterButton
        :loading="loading"
      />
      <a-tree
        v-if="flag == 1"
        showLine
        checkStrictly
        :selectedKeys="selectedKeys"
        :defaultExpandAll="false"
        :autoExpandParent="false"
        :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
        :treeData="DataSource"
        :expandedKeys.sync="expandedKeys"
        @select="handleTreeSelect"
        @expand="handleTreeExpand"
      />
      <a-table
        size="middle"
        class="noneHeard"
        v-if="flag == 2"
        :columns="columns"
        :data-source="DataSource"
        :pagination="ipagination"
        @change="handleTableChange"
      >
        <template style="text-align: center" slot="departName" slot-scope="text, record, index">
          <a-tooltip placement="topLeft" :title="text">
            <div @click="handleTableselctRow(record, index)" :class="{ active: activeIndex == index }">
              <i class="v-line" /><a-icon type="file" style="margin-right: 4px" />{{ text }}
            </div>
          </a-tooltip>
        </template>
      </a-table>
    </a-spin>
  </a-card>
</template>

<script>
import { queryMyDeptTreeByParentIds, searchByKeywords } from '@/api/api'
import { getAction } from '@/api/manage'
export default {
  name: 'AddressListMid',
  data() {
    return {
      searchValue: '',
      cardLoading: true,
      loading: false,
      DataSource: [],
      selectedKeys: [],
      url: {
        treelist: '/sjyzzx/sjZxzyUnit/queryFinSysOrgInfo',
        depart: '/sys/sysDepart/queryFinDeptChange',
        searchBy: '/sjyzzx/sjZxzyUnit/searchBy'
      },
      queryParam: {
        // TODO 账套id -----
        id: '',
        accName: '',
        ifRoot: false
        // TODO 账套 -----
        // isChildren:''
      },
      // 1:树 2:列表
      flag: 1,
      columns: [
        {
          title: '单位名称',
          dataIndex: 'departName',
          ellipsis: true,
          scopedSlots: { customRender: 'departName' }
        }
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      disableMixinCreated: true,
      expandedKeys: [],
      activeIndex: undefined
    }
  },
  props: ['value', 'ifRoot'],
  watch: {
    value: {
      handler(orgCode) {
        console.log('orgCode----->', orgCode)
        // 根据orgCode 去查询 公司的id
        if (orgCode) this.getDeptChange(orgCode)
      }
    },
    ifRoot: {
      immediate: true,
      handler(ifRoot) {
        console.log('ifRoot----->', ifRoot)
        this.queryParam.ifRoot = ifRoot
      }
    }
  },
  methods: {
    handleTableselctRow(record, index) {
      this.activeIndex = index
      console.log(record)
      if (Object.keys(record).length != 0) {
        this.$emit('unitId', record.value || '', record.title)
      }
    },
    queryTreeData() {
      this.commonRequestThen(getAction(this.url.treelist, this.queryParam))
    },
    getTableData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let param = {
        current: this.ipagination.current,
        pageSize: this.ipagination.pageSize
      }
      this.commonRequestThen(
        getAction(this.url.searchBy, Object.assign({}, { keyWord: this.searchValue }, this.queryParam, param))
      )
    },
    handleSearch(value) {
      debugger
      this.$emit('unitId', '', '')
      if (value) {
        // 生成列表
        this.flag = 2
        this.getTableData(1)
      } else {
        // 显示为树
        this.flag = 1
        this.queryTreeData()
        this.selectedKeys = []
      }
    },
    //选中
    handleTreeSelect(selectedKeys, event) {
      if (selectedKeys.length > 0 && this.selectedKeys[0] !== selectedKeys[0]) {
        this.selectedKeys = [selectedKeys[0]]
        console.log('this.selectedKeys -------->', this.selectedKeys)
        this.$emit('unitId', this.selectedKeys[0], event.node.title)
      }
    },
    handleTableChange(pagination, filters, sorter) {
      debugger
      this.ipagination = pagination
      this.getTableData()
    },
    emitInput(orgCode) {
      this.$emit('input', orgCode)
    },

    commonRequestThen(promise) {
      this.loading = true
      this.DataSource = []
      promise
        .then(res => {
          if (res.success) {
            this.expandedKeys = []
            let data = res.result.records || res.result
            this.ipagination.total = res.result.total || 0
            // update-begin- --- author:wangshuai ------ date:20200102 ---- for:去除默认选中第一条数据、默认展开所有第一级
            if (data.length > 0) {
              data.forEach((item, index) => {
                // 默认选中第一条数据、默认展开所有第一级且有子项
                if (index === 0) {
                }
                item.isLeaf = item.ifLow == '1' || item.ifLow == null ? true : false
              })
            }
            console.log(data)
            this.DataSource = data
            // update-end- --- author:wangshuai ------ date:20200102 ---- for:去除默认选中第一条数据、默认展开所有第一级
          } else {
            this.$message.warn(res.message)
            console.error('组织机构查询失败:', res)
          }
        })
        .finally(() => {
          this.loading = false
          this.cardLoading = false
        })
    },
    // 获取unitId
    getDeptChange(id) {
      this.flag = 1
      this.searchValue = ''
      getAction(this.url.depart, { id }).then(res => {
        if (res.success) {
          this.queryParam.id = res.result
        } else {
          this.queryParam.id = ''
        }
        this.queryTreeData()
      })
    },
    // 科目编码下拉树结构
    handleTreeExpand(expandedKeys, { expanded, node }) {
      console.log(node.dataRef.abrName)
      if (expanded) {
        const _this = this
        let childTree = []
        if (node.dataRef.children) {
          // 有值了直接渲染
          return
        }
        // 没有值根据当前父节点获取下面子节点并挂在树节点中，添加到对应父节点的children中
        getAction(this.url.treelist, { id: node.dataRef.id }).then(res => {
          this.loading = false
          if (res.success) {
            res.result.map(item => {
              item.isLeaf = item.ifLow == '1' ? true : false
              childTree.push(item)
            })
            node.dataRef.children = [...childTree]
            this.DataSource = [...this.DataSource]
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.noneHeard {
  /deep/ .ant-table-thead {
    display: none;
  }
  /deep/ .ant-table-tbody .ant-table-row td {
    padding: 8px 0px !important;
  }
  /deep/ .ant-table-tbody > tr > td {
    border: none;
  }
  .v-line {
    position: absolute;
    left: 6px;
    width: 1px;
    height: 10px;
    margin: 22px 0 0;
    border-left: 1px solid #d9d9d9;
  }
  /deep/ .ant-table-row-cell-ellipsis {
    cursor: pointer;
  }
  /deep/.ant-table-row:focus {
    background-color: #bae7ff;
  }
  /deep/ .ant-table-row:last-child {
    .v-line {
      display: none;
    }
  }
}
.active{
  background-color: #1890ff3d;
}
</style>
